<?php

namespace app\admin\controller\community\config;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\community\project\Community as CommunityModel;

/**
 * 社区代码配置管理
 *
 * @icon fa fa-home
 */
class Community extends Backend
{
    /**
     * Community模型对象
     * @var \app\admin\model\community\config\Community
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\community\config\Community;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            // 获取URL中传递的参数
            $community_id = $this->request->param('community_id', 0);
            $publicwelfare_id = $this->request->param('publicwelfare_id', 0);

            // 自动生成社区代码（仅在该社区下为空时）
            if ($community_id > 0) {
                $this->autoGenerateCommunityCodes($community_id,$publicwelfare_id);
            }

            $searchFields = ['id', 'code', 'remark'];
            $sortFields = ['id', 'code', 'community_id', 'status', 'weigh', 'createtime', 'updatetime'];
            
            list($where, $sort, $order, $offset, $limit) = $this->buildparams($sortFields, $searchFields);
            $where = [];

            
            // 如果有传递参数，则添加到查询条件中
            if ($community_id > 0) {
                $where['fa_community_code_config.community_id'] = $community_id;
            }

            if ($publicwelfare_id > 0) {
                $where['fa_community_code_config.publicwelfare_id'] = $publicwelfare_id;
            }

            // 使用数字填充的方式对code进行排序
            $sort = 'id';
            $order = 'asc';
            
            $list = $this->model
                ->with(['communityinfo'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
                
            $result = ['total' => $list->total(), 'rows' => $list->items()];
            
            return json($result);
        }

        
        
        // 获取URL中传递的参数并传递给视图
        $community_id = $this->request->param('community_id', 0);
        $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
        $this->view->assign('community_id', $community_id);
        $this->view->assign('publicwelfare_id', $publicwelfare_id);
        
        // 如果通过网址传入了community_id和publicwelfare_id，则设置一个标记，用于控制视图中的字段显示
        $simplifiedView = ($community_id > 0 || $publicwelfare_id > 0);
        $this->view->assign('simplifiedView', $simplifiedView);
        
        return $this->view->fetch();
    }
    
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                // 从 URL 参数中获取 community_id 和 publicwelfare_id
                $community_id = $this->request->param('community_id', 0);
                $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
                
                // 如果表单没有提交这些值，但 URL 中有，则自动填充
                if (!isset($params['community_id']) && $community_id > 0) {
                    $params['community_id'] = $community_id;
                }
                if (!isset($params['publicwelfare_id']) && $publicwelfare_id > 0) {
                    $params['publicwelfare_id'] = $publicwelfare_id;
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取社区列表
        $communityList = \app\admin\model\Community::where('status', 1)->column('name', 'id');
        $this->view->assign('communityList', $communityList);

        // 获取公益项目列表
        $publicwelfareList = \app\admin\model\community\Publicwelfare::where('status', 1)->column('project_name', 'id');
        $this->view->assign('publicwelfareList', $publicwelfareList);
        
        // 获取当前用户所属社区和URL参数
        $user = $this->auth->getUserInfo();
        $community_id = $this->request->param('community_id', $user['community_id'] ?? 0);
        $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
        $this->view->assign('community_id', $community_id);
        $this->view->assign('publicwelfare_id', $publicwelfare_id);
        
        // 查询未被选取的社区列表
        $communityCodeList = [];
        if ($community_id > 0) {
            // 查询已经配置的社区代码
            $existingNames = $this->model
                ->where('community_id', $community_id)
                ->column('name');
            foreach ($existingNames as $key=>$name) {
                $existingNames[$key] = preg_replace('/^.*-\s*/', '', $name);
            }
            
            // 查询所有可用的社区代码，并连接 cityarea 表查询 district_id 的名字
            $allCommunities = model("Ocation")->alias('o')
                ->join('fa_cityarea c', 'o.district_id = c.id', 'LEFT')
                ->where("o.rel_type", 2)
                ->where("o.rel_id", $community_id)
                ->where('o.address_lv_octionlevel', '>', 1)
                ->field('o.*, c.name as district_name')
                ->select();

            $communityCodeList = [];
            // 过滤出未被选取的社区代码和当前社区代码
            foreach ($allCommunities as $community) {
                $communityName = isset($community['name']) ? $community['name'] : $community['id'];
                $districtName = isset($community['district_name']) ? $community['district_name'] : '';

                // 将区域名称添加到社区名称前面
                $fullName = $districtName ? "$districtName - $communityName" : $communityName;

                if (!in_array($communityName, $existingNames)) {
                    $communityCodeList[$communityName] = $fullName;
                }
            }
        }
        $this->view->assign('communityCodeList', $communityCodeList);
        
        // 如果通过网址传入了community_id和publicwelfare_id，则设置一个标记，用于控制视图中的字段显示
        $simplifiedView = ($community_id > 0 || $publicwelfare_id > 0);
        $this->view->assign('simplifiedView', $simplifiedView);
        $this->assignconfig('community_id', $community_id);
        $this->assignconfig('publicwelfare_id', $publicwelfare_id);
        return $this->view->fetch();
    }
    
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取URL参数和当前用户所属社区
        $user = $this->auth->getUserInfo();
        $community_id = $this->request->param('community_id', $user['community_id'] ?? 0);
        $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
        
        // 获取社区列表，转换为键值对格式
        $communityListData = model("Ocation")->alias('o')
            ->join('fa_cityarea c', 'o.district_id = c.id', 'LEFT')
            ->where("o.rel_type", 2)
            ->where("o.rel_id", $community_id)
            ->where('o.address_lv_octionlevel', '>', 1)
            ->field('o.*, c.name as district_name')
            ->select();
            
        $communityList = [];
        foreach ($communityListData as $item) {
            $communityName = isset($item['name']) ? $item['name'] : $item['id'];
            $districtName = isset($item['district_name']) ? $item['district_name'] : '';
            $fullName = $districtName ? "$districtName - $communityName" : $communityName;
            $communityList[$item['id']] = $fullName;
        }
        $this->view->assign('communityList', $communityList);

        // 获取公益项目列表
        $publicwelfareList = \app\admin\model\community\Publicwelfare::where('status', 1)->column('project_name', 'id');
        $this->view->assign('publicwelfareList', $publicwelfareList);

        $this->view->assign('community_id', $community_id);
        $this->view->assign('publicwelfare_id', $publicwelfare_id);
        
        // 查询未被选取的社区列表
        $communityCodeList = [];
        if ($community_id > 0) {
            // 获取当前记录的名称（用于后面保留在选项中）
            $currentName = '';
            if ($row && !empty($row['name'])) {
                $currentName = preg_replace('/^.*-\s*/', '', $row['name']);
            }

            // 查询已经配置的社区代码，排除当前正在编辑的记录
            $existingNames = $this->model
                ->where('community_id', $community_id)
                ->where('id', '<>', $ids) // 排除当前正在编辑的记录
                ->column('name');
            foreach ($existingNames as $key=>$name) {
                $existingNames[$key] = preg_replace('/^.*-\s*/', '', $name);
            }

            // 查询所有可用的社区代码，并连接 cityarea 表查询 district_id 的名字
            $allCommunities = model("Ocation")->alias('o')
                ->join('fa_cityarea c', 'o.district_id = c.id', 'LEFT')
                ->where("o.rel_type", 2)
                ->where("o.rel_id", $community_id)
                ->where('o.address_lv_octionlevel', '>', 1)
                ->field('o.*, c.name as district_name')
                ->select();

            $communityCodeList = [];
            // 过滤出未被选取的社区代码和当前社区代码
            foreach ($allCommunities as $community) {
                $communityName = isset($community['name']) ? $community['name'] : $community['id'];
                $districtName = isset($community['district_name']) ? $community['district_name'] : '';

                // 将区域名称添加到社区名称前面
                $fullName = $districtName ? "$districtName - $communityName" : $communityName;

                // 如果社区名称不在已存在列表中，或者是当前正在编辑的记录的名称，则添加到选项列表中
                if (!in_array($communityName, $existingNames) || $communityName == $currentName) {
                    $communityCodeList[$communityName] = $fullName;
                }
            }
            
            // 如果选项列表为空，则添加当前记录的名称作为选项
            if (empty($communityCodeList) && !empty($row['name'])) {
                $communityCodeList[$currentName] = $row['name'];
            }
        }
        $this->view->assign('communityCodeList', $communityCodeList);
        
        // 如果通过网址传入了community_id和publicwelfare_id，则设置一个标记，用于控制视图中的字段显示
        $simplifiedView = ($community_id > 0 || $publicwelfare_id > 0);
        $this->view->assign('simplifiedView', $simplifiedView);
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    
    /**
     * 删除
     */
    function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        try {
            // 获取要删除的记录，以便获取其community_id
            $records = $this->model->where('id', 'in', $ids)->select();
            $communityIds = [];

            foreach ($records as $record) {
                $communityIds[] = $record['community_id'];
            }

            // 强制删除记录
            $result = $this->model->where('id', 'in', $ids)->delete();

            if ($result) {
                // 对每个community_id重新排序课程代码
                $uniqueCommunityIds = array_unique($communityIds);

                foreach ($uniqueCommunityIds as $communityId) {
                    $this->reorderCourseCodes($communityId);
                }

                // 使用FastAdmin框架标准的成功返回格式
                return json(['code' => 1, 'msg' => __('Delete successful')]);
            } else {
                $this->error(__('No rows were deleted'));
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }


    protected function autoGenerateCommunityCodes($community_id,$publicwelfare_id){
        $count = $this->model->where('community_id', $community_id)->where('publicwelfare_id',$publicwelfare_id)->count();
        $district_id = \think\Db::name('fa_community')->where('id', $community_id)->value('district_id');
        if ($count == 0) {
            $Communitys=\think\Db::name('fa_ocation')->where('district_id', $district_id)->where('address_lv_octionlevel',2)->select();
            $insertData = [];
            foreach ($Communitys as $k => $Community) {
                $insertData[] = [
                    'community_id' => $community_id,
                    'publicwelfare_id' => $publicwelfare_id,
                    'name' => $Community['name'],
                    'code' => '社区' . ($k + 1),
                    'createtime' => time(),
                    'updatetime' => time(),
                    'status' => 1
                ];
            }
            if (!empty($insertData)) {
                $this->model->insertAll($insertData);
            }
        }
    }

    /**
     * 自动生成课程代码（仅在该社区下为空时）
     */
    protected function autoGenerateCourseCodes($community_id,$publicwelfare_id)
    {
        $count = $this->model->where('community_id', $community_id)->where('publicwelfare_id',$publicwelfare_id)->count();
        if ($count == 0) {
            $district_id=\think\Db::name('fa_community')->where('id', $community_id)->value('district_id');
            $courses = \think\Db::name('fa_ocation')->where('rel_type', 2)->where('rel_id', $community_id)->where('district_id',$district_id)->where('address_lv_octionlevel',2)->select();
            $insertData = [];
            foreach ($courses as $k => $course) {
                $insertData[] = [
                    'community_id' => $community_id,
                    'publicwelfare_id' => $publicwelfare_id,
                    'name' => $course['name'],
                    'code' => '社区' . ($k + 1),
                    'createtime' => time(),
                    'updatetime' => time(),
                    'status' => 1
                ];
            }
            if (!empty($insertData)) {
                $this->model->insertAll($insertData);
            }
        }
    }

    /**
     * 删除后重排课程代码
     */
    protected function reorderCourseCodes($community_id)
    {
        $codes = $this->model->where('community_id', $community_id)->order('id asc')->select();
        foreach ($codes as $k => $row) {
            $this->model->where('id', $row['id'])->update(['code' => '社区' . ($k + 1)]);
        }
    }

    /**
     * 更新所有社区的课程代码
     * 自动生成社区1、社区2、社区3...格式的代码
     */
    protected function updateAllCommunityCourseCode()
    {
        // 获取所有课程
        $courses = Db::name('community_config_course')->where('status', 1)->select();
        if (!$courses) {
            return;
        }
        
        // 获取所有社区项目
        $communities = Db::name('fa_community')->where('status', 1)->order('id asc')->select();
        if (!$communities) {
            return;
        }
        
        // 删除现有的社区课程代码记录
        Db::name('community_course_code')->where('id', '>', 0)->delete();
        
        // 为每个社区生成课程代码
        $insertData = [];
        $codeIndex = 1;
        
        foreach ($communities as $community) {
            foreach ($courses as $course) {
                $insertData[] = [
                    'community_id' => $community['id'],
                    'course_id' => $course['id'],
                    'code' => '社区' . $codeIndex,
                    'create_time' => time(),
                    'update_time' => time(),
                    'status' => 1
                ];
                $codeIndex++;
            }
        }
        
        // 批量插入新的课程代码记录
        if (!empty($insertData)) {
            Db::name('community_course_code')->insertAll($insertData);
        }
    }
}
